package leetcode.easy.limit50;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class No56 {
    public static void main(String[] args) {

        int[][] intervals = new int[][]{{1, 4}, {0, 2}, {3, 5}};
        No56 no56 = new No56();
        int[][] merge = no56.merge(intervals);
        System.out.println(Arrays.toString(merge));

    }

    public int[][] merge(int[][] intervals) {
        if (intervals.length == 0) {
            return new int[0][0];
        }
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });
        List<int[]> list = new ArrayList<>();
        for (int i = 0; i < intervals.length; i++) {
            int[] curr = intervals[i];
            int left = curr[0];
            int right = curr[1];
            if (list.isEmpty()) {
                list.add(new int[]{left, right});
                continue;
            }
            if (list.get(list.size() - 1)[1] >= left) {
                list.get(list.size() - 1)[1] = Math.max(list.get(list.size() - 1)[1], right);
            } else {
                list.add(new int[]{left, right});
            }
        }
        return list.toArray(new int[list.size()][]);
    }
}
